package com.jtbd.service.campus;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jtbd.domain.Course;
import com.jtbd.handler.GetSecurityUserHandler;
import com.jtbd.mapper.CourseMapper;
import com.jtbd.util.JtbdPageUtil;
import com.jtbd.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class CourseService {
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 获取课程列表
     */
    public IPage<Course> getCourseList(Long campusId, IPage<Course> page) {
        if (ObjectUtils.isEmpty(campusId)) return new Page<>();
        if (ObjectUtils.isEmpty(page)) {
            page = Page.of(1, 10);
        }
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Course::getCampusId, campusId);
        return courseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 按条件查询课程列表
     */
    public IPage<Course> getCourseListByCondition(Long campusId, Integer courseStatus, Integer courseLevel, Integer courseCategory, Integer courseType, String courseName, IPage<Course> page) {
        if (ObjectUtils.isEmpty(page)) page = JtbdPageUtil.getPage();
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(campusId)) queryWrapper.eq(Course::getCampusId, campusId);
        if (!ObjectUtils.isEmpty(courseType)) queryWrapper.eq(Course::getCourseType, courseType);
        if (!ObjectUtils.isEmpty(courseStatus)) queryWrapper.eq(Course::getCourseStatus, courseStatus);
        if (!ObjectUtils.isEmpty(courseLevel)) queryWrapper.eq(Course::getCourseLevel, courseLevel);
        if (!ObjectUtils.isEmpty(courseCategory)) queryWrapper.eq(Course::getCourseCategory, courseCategory);
        if (!ObjectUtils.isEmpty(courseName)) queryWrapper.like(Course::getCourseName, courseName);
        return courseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 创建课程
     *
     * @param course 课程信息
     * @return 新增的课程ID
     */
    public Long addCourse(Course course) {
        if (!ObjectUtils.isEmpty(course)) {
            if (ObjectUtils.isEmpty(course.getCreateId())) {
                Long operateUserId = GetSecurityUserHandler.getSecurityUserId();
                course.setCreateId(operateUserId);
                course.setUpdateId(operateUserId);
            }
            int insertResult = courseMapper.insert(course);
            return insertResult > 0 ? course.getId() : null;
        }
        return null;
    }
}
